package cn.wen233.core.config;

import cn.wen233.core.utils.IocUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * config
 *
 * 通过AutoConfiguration spi自动装配
 * 启用MapperScan扫描
 * 启用SunglowProperty配置类
 * 扫描cn.wen233目录下的组件
 *
 * @author wenei
 * @date 2021-10-23 12:03
 */
@Configuration
@MapperScan("cn.wen233.core.mapper")
@EnableConfigurationProperties(SunglowProperty.class)
@ComponentScan("cn.wen233")
@RequiredArgsConstructor
public class SunglowConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(SunglowConfig.class);

    private final SunglowProperty appProperty;

    /**
     * 根据应用的配置使用相关数据源
     */
    @Bean(name = "sunglowDerbyDataSource")
    @ConditionalOnProperty(prefix = "sunglow.support", name = "datasource", havingValue = "derby")
    public DataSource sunglowDerbyDataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(appProperty.getDerbyDriverClassName());
        hikariConfig.setJdbcUrl(appProperty.getDerbyUrl());
        LOGGER.info("数据源设置为：derby");
        return new HikariDataSource(hikariConfig);
    }

    @Bean(name = "sunglowMysqlDataSource")
    @ConditionalOnProperty(prefix = "sunglow.support", name = "datasource", havingValue = "mysql")
    public DataSource sunglowMysqlDataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(appProperty.getMysqlDriverClassName());
        hikariConfig.setJdbcUrl(appProperty.getMysqlUrl());
        hikariConfig.setUsername(appProperty.getMysqlUsername());
        hikariConfig.setPassword(appProperty.getMysqlPassword());
        LOGGER.info("数据源设置为：mysql");
        return new HikariDataSource(hikariConfig);
    }

    @Bean(name = "iocUtils")
    public IocUtils iocUtils() {
        return new IocUtils();
    }
}
